package com.train.controller;

import com.train.pojo.Course;
import com.train.pojo.Department;
import com.train.pojo.Employee;
import com.train.service.CourseService;
import com.train.service.DepartmentService;
import com.train.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collection;

@Controller
public class DepController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private CourseService courseService;

    //查询所有考勤卡，返回列表页面
    @GetMapping("/dep")
    public String list(@ModelAttribute("msg")String msg, @ModelAttribute("msg")String msgCode, Model model){
        Collection<Department> departments = departmentService.selectAllDepartment();
//        将结果放在请求中
        model.addAttribute("departments",departments);
        return "dep/depList.html";
    }

    @GetMapping("/addDep")
    public String toAdd(){
        return "dep/addDep.html";
    }

    //员工添加功能，使用post接收
    @PostMapping("/addDep")
    public String add(Department department,RedirectAttributes rettr){
        //保存员工信息
        departmentService.addDepartment(department);
        rettr.addFlashAttribute("" +
                "msg","部门添加成功");
        rettr.addFlashAttribute("msgCode","200");
        //回到员工列表页面，可以使用redirect或者forward
        return "redirect:/dep";
    }

    @GetMapping("/delDep/{id}")
    public String deleteEmp(@PathVariable("id")Integer id, RedirectAttributes rettr){
        //根据id删除员工
        Collection<Employee> employees=employeeService.selectEmployeeByDepid(id);
        Collection<Course> courses=courseService.getCourseBydepid(id);
        if (employees.isEmpty()&&courses.isEmpty()){
            departmentService.deleteDepartment(id);
            rettr.addFlashAttribute("" +
                    "msg","部门删除成功");
            rettr.addFlashAttribute("msgCode","200");
            return "redirect:/dep";
        }
        else {
            rettr.addFlashAttribute("" +
                    "msg","部门删除失败，该部门存在关联记录，无法删除！");
            rettr.addFlashAttribute("msgCode","400");
            return "redirect:/dep";
        }
    }
}

